package com.shunda.consumer.controller;

import com.shunda.common.annotation.Log;
import com.shunda.common.config.ShunDaConfig;
import com.shunda.common.constant.Constants;
import com.shunda.common.core.controller.BaseController;
import com.shunda.common.core.domain.AjaxResult;
import com.shunda.common.core.domain.entity.SysDept;
import com.shunda.common.core.domain.entity.SysUser;
import com.shunda.common.core.page.TableDataInfo;
import com.shunda.common.enums.BusinessType;
import com.shunda.common.utils.StringUtils;
import com.shunda.common.utils.bean.BeanUtils;
import com.shunda.common.utils.file.FileUploadUtils;
import com.shunda.common.utils.file.MimeTypeUtils;
import com.shunda.consumer.domain.ConsumerUser;
import com.shunda.consumer.domain.LoginConsumerUser;
import com.shunda.consumer.service.IConsumerUserService;
import com.shunda.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author: dongyq
 * @date: 2025/3/8 16:31
 * @since: 1.0.0
 * @功能描述:
 */
@RestController
@RequestMapping("/web/user")
public class ConsumerController extends BaseController {

    @Autowired
    private IConsumerUserService consumerUserService;

    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 客户注册接口（user_type：01），直接登录成功，并返回token
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody LoginConsumerUser loginConsumerUser) {
        try {
            registerCheck(loginConsumerUser);
        } catch (Exception e) {
            return error(e.getMessage());
        }
        try {
            consumerUserService.verifyCode(loginConsumerUser.getPhonenumber(), loginConsumerUser.getCode());
        } catch (Exception e) {
            return error(e.getMessage());
        }
        // 判断加油站注册用户是否已满
        SysDept sysDept = sysDeptService.selectDeptById(loginConsumerUser.getDeptId());
        if (sysDept == null) {
            return error("用户注册失败，【" + loginConsumerUser.getDeptId() + "】加油站不存在！");
        }
        sysDept.setHaveCarCount(sysDept.getHaveCarCount() + 1);
        if (sysDept.getHaveCarCount() > sysDept.getVipCount()) {
            return error("用户注册失败，【" + sysDept.getDeptName() + "】加油站已满！");
        }
        // 判断手机号是否已存在
        if (!consumerUserService.checkUserNameUnique(loginConsumerUser.getUserName())
                || !consumerUserService.checkPhoneUnique(loginConsumerUser.getPhonenumber())) {
            return error("用户注册失败，【" + loginConsumerUser.getPhonenumber() + "】手机号已存在！");
        }
        ConsumerUser consumerUser = new ConsumerUser();
        BeanUtils.copyBeanProp(consumerUser, loginConsumerUser);
        consumerUserService.insertTo(consumerUser);
        String token = consumerUserService.loginGetToken(consumerUser);
        consumerUserService.updateTo(consumerUser, loginConsumerUser);
        sysDeptService.updateDept(sysDept);
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    public void registerCheck(LoginConsumerUser loginConsumerUser) throws Exception {
        if (StringUtils.isEmpty(loginConsumerUser.getCode())) {
            throw new RuntimeException("用户注册失败，验证码为空！");
        }
        if (StringUtils.isEmpty(loginConsumerUser.getPhonenumber())) {
            throw new RuntimeException("用户注册失败，手机号为空！");
        }
        if (loginConsumerUser.getDeptId() == null || loginConsumerUser.getDeptId() < 0) {
            throw new RuntimeException("用户注册失败，所属加油站ID为空！");
        }
        if (StringUtils.isEmpty(loginConsumerUser.getUserName())) {
            throw new RuntimeException("用户注册失败，登录账号为空！");
        }
    }

    /**
     * 获取验证码接口
     */
    @GetMapping("/getCaptcha")
    public AjaxResult getCaptcha(String phone) {
        try {
            consumerUserService.getCaptcha(phone);
        } catch (Exception e) {
            return error(e.getMessage());
        }
        return success();
    }

    /**
     * 客户登录接口
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginConsumerUser loginConsumerUser) {
        String phone = loginConsumerUser.getPhonenumber();
        try {
            consumerUserService.verifyCode(phone, loginConsumerUser.getCode());
        } catch (Exception e) {
            return error(e.getMessage());
        }
        String token = null;
        // 查看该手机号是否是已注册
        ConsumerUser consumerUserByPhone = consumerUserService.selectConsumerUserByPhone(phone);
        if (consumerUserByPhone != null && consumerUserByPhone.getUserId() > 0) {
            token = consumerUserService.loginGetToken(consumerUserByPhone);
            consumerUserService.updateTo(consumerUserByPhone, loginConsumerUser);
        } else {
            return error("登录失败，手机号未注册");
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 客户登出接口
     */
    @PostMapping("/loginout")
    public AjaxResult loginOut(@RequestBody LoginConsumerUser consumerUser) {
        consumerUserService.loginOut(consumerUser);
        return success();
    }

    /**
     * 修改个人信息接口
     */
    @PutMapping("/update")
    public AjaxResult update(@RequestBody ConsumerUser consumerUser) {
        String phone = consumerUser.getPhonenumber();
        if (StringUtils.isEmpty(phone)) {
            return error("修改用户失败，手机号不可为空！");
        } else {
            consumerUserService.updateTo(consumerUser, null);
        }
        return success();
    }

    /**
     * 头像上传
     */
    @Log(title = "客户图像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            String avatar = FileUploadUtils.upload(ShunDaConfig.getWebUserAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", avatar);
            return ajax;
        }
        return error("上传图片异常，请联系管理员");
    }

    /**
     * 获取个人信息接口
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo(String phone) {
        ConsumerUser consumerUser = consumerUserService.selectConsumerUserByPhone(phone);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", consumerUser);
        return ajax;
    }

    /**
     * 获取加油站列表接口
     */
    @GetMapping("/getStationList")
    public AjaxResult getStationList() {
        List<SysDept> stationList = sysDeptService.selectStationList();
        return success(stationList);
    }

    /**
     * 获取常用加油站接口
     */
    @GetMapping("/getCustomerStationsList")
    public AjaxResult getCustomerStationsList(String phone, int top) {
        List<SysDept> stationList = consumerUserService.selectRecordByPhoneAndTop(phone, top);
        return success(stationList);
    }

    /**
     * 订单列表
     */
    @GetMapping("/getOrderList")
    public TableDataInfo getOrderList(String phone) {
        return consumerUserService.selectOrderPageByPhone(phone);
    }

    /**
     * 提现记录
     */
    @GetMapping("/getWithdrawList")
    public TableDataInfo getWithdrawList(String phone) {
        return consumerUserService.selectWithdrawPageByPhone(phone);
    }

    /**
     * 用户提现申请接口
     */

    /**
     * 根据加油站获取加油员、班长接口
     */
    @GetMapping("/getSalesmanList")
    public AjaxResult getSalesmanList(Long deptId) {
        List<SysUser> salesmanList = consumerUserService.selectSalesmanList(deptId);
        return success(salesmanList);
    }

    /**
     * 获取用户当日资金池金额接口
     */
    @GetMapping("/getFundPool")
    public AjaxResult getFundPool() {
        BigDecimal fundPoolTotalAmount = consumerUserService.selectFundPoolTotalAmount();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("fundPool", fundPoolTotalAmount);
        return ajax;
    }

}
